/**
 * Date:2019年9月29日 下午2:46:37
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved
 */

package com.app.common.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Description: 统一返回结果 <br/>
 * Date:2019年9月29日 下午2:46:37 <br/>
 * 
 * @author xuejianxin
 */
@ControllerAdvice(basePackages = "com.app.action")
public class AppResponseWrapper implements ResponseBodyAdvice<Object> {

	@Autowired
	private ObjectMapper om;

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		if (body instanceof String) {// 返回字符串时需要特殊处理，否则转化错误
			AppResponse aResponse = new AppResponse();
			aResponse.success(body);
			// ObjectMapper om = new ObjectMapper();
			try {
				return om.writeValueAsString(aResponse);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		} else if (!(body instanceof AppResponse)) {
			AppResponse aResponse = new AppResponse();
			aResponse.success(body);
			return aResponse;
		}

		AppResponse aResponse = new AppResponse();
		aResponse.error("-1", "消息转化错误!");
		return aResponse;

	}

	

}